<template>
  <div id="player-tmp">

    <!-- 左边播放器按钮 -->
    <div class="player-btn">
      <!-- 手机端播放模式 -->
      <div @click="handlerMode" class="mobile-playMode">
        <!-- {{ playModeList[currentPlayMode].n }} -->
        <i class="el-icon-refresh" v-if="currentPlayMode === 0" title="列表循环"></i>
        <i class="el-icon-sort" v-else-if="currentPlayMode === 1" title="随机播放"></i>
        <i class="el-icon-c-scale-to-original" v-else-if="currentPlayMode === 2" title="单曲循环"></i>
      </div>

      <!-- 上一曲 -->
      <div @click="handlerPrev" title="上一曲">
        <i class="el-icon-arrow-left"></i>
      </div>

      <!-- 暂停/播放 -->
      <div @click="handlerPause" title="暂停/播放">
        <div v-if="isPlaying"><i class="el-icon-video-pause"></i></div>
        <div v-else><i class="el-icon-video-play"></i></div>
      </div>

      <!-- 下一曲 -->
      <div @click="handlerNext" title="下一曲">
        <div>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>

      <!-- 手机端展开播放列表 -->
      <div class="mobile-playList" @click="mobileMenu=true">
        <i class="el-icon-s-operation"></i>
      </div>
    </div>

    <!-- 音乐进度条 -->
    <aplayer :autoplay="autoPlay" :volume="volume/100" :music="musicList[currentMusicIndex]" repeat="music">
    </aplayer>

    <!-- 右边音量条 -->
    <div class="player-volume">

      <!-- 播放模式 -->
      <div @click="handlerMode">
        <!-- {{ playModeList[currentPlayMode].n }} -->
        <i class="el-icon-refresh" v-if="currentPlayMode === 0" title="列表循环"></i>
        <i class="el-icon-sort" v-else-if="currentPlayMode === 1" title="随机播放"></i>
        <i class="el-icon-c-scale-to-original" v-else-if="currentPlayMode === 2" title="单曲循环"></i>
      </div>

      <!-- 收藏 -->
      <div @click="handlerLike">
        <i style="color: crimson; font-size: 21px;" class="el-icon-star-on option-btn" v-if="musicList[currentMusicIndex].loved" title="取消收藏" @click="cancelCollectMusic(musicList[currentMusicIndex])"></i>
        <i v-else class="el-icon-star-off option-btn" title="添加收藏" @click="collectMusic(musicList[currentMusicIndex])"></i>
      </div>

      <!-- 静音 -->
      <div @click="handlerMute" title="音量">
        <i class="el-icon-phone-outline" v-if="apparentVolume > 0"></i>
        <i class="el-icon-phone" v-else></i>
      </div>

      <!-- 调节音量条 -->
      <div class="volume-bar">
        <el-slider :show-tooltip="false" v-model="apparentVolume" @input="switchVolume"></el-slider>
        <!-- <mt-range v-model="volume"></mt-range> -->
      </div>
    </div>

    <!-- 手机端播放列表 -->
    <el-drawer :visible.sync="mobileMenu" size="76%" :with-header="false" direction="btt">
      <div class="swiper-container">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-for="(v, i) in mobileMusicList" :key="i">
            <div>
              <div class="title">
                <span>{{ v.title }}<b> ({{ v.num }})</b></span>
                <i class="el-icon-delete" @click="deleteAll(i)"></i>
              </div>
              <ul class="music-list">
                <transition-group enter-active-class="animate__animated animate__bounce" leave-active-class="animate__animated animate__fadeOutLeft">
                  <li v-for="(m,n) in v.list" :key="m.time" @click="handlerMobileList(m,n,i)" :class="highLight(i, m)">
                    <span class="name">{{ m.title }}
                      <span class="artist"> - {{ m.artist }}</span>
                    </span>
                    <i class="el-icon-close" @click.stop="deleteOne(m,i)"></i>
                  </li>
                </transition-group>
              </ul>
            </div>
          </div>
        </div>
        <!-- 如果需要分页器 -->
        <div class="swiper-pagination"></div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Aplayer from 'vue-aplayer'
import { mapState, mapMutations } from 'vuex'
import { formatLyricsByKuGou } from '../api/KuGou'
import { formatLyricsByMiGU } from '../api/MiGu'
import { formatLyricsByNetease } from '../api/Netease'

export default {
  components: {
    Aplayer
  },
  props: {
    musicList: {
      type: Array,
      required: true
    },
  },
  computed: {
    ...mapState([
      'currentPlayMusicIndex',
      'isPlaying',
      'lovedList',
      'playList',
      'recordList',
    ]),
  },
  data () {
    return {
      autoPlay: false, // 自动播放
      volume: 20, // 播放音量 0-100
      apparentVolume: 20, // 外显音量
      beforeMutedVolume: 20, // 静音前的音量
      currentPlayMode: 0, // 当前播放模式
      playModeList: [
        { m: 0, n: '列表循环' },
        { m: 1, n: '随机播放' },
        { m: 2, n: '单曲循环' },
        // { m: 2, n: '顺序播放' },
      ], // 播放模式 
      hasPlayedMusicNum: 0, // 已播放音乐数，用于顺序播放
      currentMusicIndex: 0,
      AudioPlayer: null, // 播放器控件
      hasCollected: true, // 是否被收藏
      mobileMenu: true, // 手机端菜单
      mobileMusicList: [
        {
          title: '当前播放',
          list: [],
          num: 0,
        },
        // {
        //   title: '我的收藏',
        //   list: [],
        //   num: 0,
        // },
        {
          title: '历史播放',
          list: [],
          num: 0,
        },
      ]
    }
  },
  watch: {
    currentPlayMusicIndex: {
      handler (newVal, OldVal) {
        // 点击第一首歌，不播放的问题
        if (OldVal === -1 && newVal === 0) {
          this.updateIMGAndLyric(newVal)
        }

        if (newVal === -1) {
          this.currentMusicIndex = 0
          return
        }

        this.currentMusicIndex = newVal

      },
      immediate: false
    },
    currentMusicIndex: {
      handler (newVal, oldVal) {
        this.updateIMGAndLyric(newVal)
      },
      // 首次绑定时是否触发
      immediate: false
    },
    playList: {
      handler (v) {
        this.mobileMusicList[0].list = v
        this.mobileMusicList[0].num = v.length
      },
      immediate: true
    },
    // lovedList: {
    //   handler (v) {
    //     this.mobileMusicList[1].list = v
    //     this.mobileMusicList[1].num = v.length
    //   },
    //   immediate: true
    // },
    recordList: {
      handler (v) {
        this.mobileMusicList[1].list = v
        this.mobileMusicList[1].num = v.length
      },
      immediate: true
    },
  },
  created () {
  },
  mounted () { // 给播放控件添加ID，和歌词绑定
    var audio = document.getElementsByTagName('audio')[0],
      that = this
    this.AudioPlayer = audio
    this.AudioPlayer.ontimeupdate = function () {

      // 将秒转为 -- 分:秒.毫秒
      let m = (parseInt(this.currentTime / 60) + '').padStart(2, '0') + ':',
        s = (parseInt(this.currentTime % 60) + '').padStart(2, '0') + '.',
        ms = parseInt(this.currentTime * 1000 % 1000)
      // 写入当前播放进度
      // console.log(this.currentTime%1000)
      // that.$store.commit('recordProgress', m + s + ms)
      that.recordProgress(this.currentTime)
      // that.$store.commit('recordProgress', this.currentTime)
    }

    this.AudioPlayer.onplay = () => {
      this.togglePlaying(true)
    }

    this.AudioPlayer.onpause = () => {
      this.togglePlaying(false)
    }

    // 音乐播放完毕绑定事件
    this.bindEnded(this.currentPlayMode)

    this.$nextTick(() => {
      // swiper配置
      this.initSwiper()
      this.mobileMenu = false
    })

  },
  methods: {
    ...mapMutations([
      'togglePlaying',
      'updatePlayIndex',
      'recordProgress',
      'updateLyrics',
      'updateSongIMG',
      'add2PlayList',
      'add2LovedList',
      'updateMusicTitle',
      'updateMusicArtist',
      'deleteOneFromPlayList',
      'deleteOneFromLovedList',
      'deleteOneFromRecordList',
      'deleteMoreFromPlayList',
      'deleteMoreFromLovedList',
      'deleteMoreFromRecordList',
    ]),

    // 索引切换，图片歌曲切换触发
    updateIMGAndLyric (newVal) {
      this.$nextTick(() => {
        this.togglePlaying(false)
        this.AudioPlayer.play()
      })

      this.updateSongIMG(this.musicList[newVal].img)
      this.updateMusicTitle(this.musicList[newVal].title)
      this.updateMusicArtist(this.musicList[newVal].artist)

      // 根据歌词不同来源格式化歌词
      switch (this.musicList[newVal].sourceId) {
        case 0: // 酷狗歌词格式化
          this.updateLyrics(formatLyricsByKuGou(this.musicList[newVal].lyrics))
          break;
        case 1: //  咪咕歌词格式化
          this.updateLyrics(formatLyricsByMiGU(this.musicList[newVal].lyrics, this.musicList[newVal].translateLyrics))
          break;
        case 2: //  QQ歌词格式化
          // this.lyrics = formatLyricsByQQ(this.musicList[newVal].lyrics)
          this.updateLyrics({})
          break;
        case 3: //  网易云歌词格式化
          this.updateLyrics(formatLyricsByNetease(this.musicList[newVal].lyrics, this.musicList[newVal].translateLyrics))
          break;
        case 4: //  酷我没歌词，直接赋空
          this.updateLyrics({})
          break;
        default:
          break;
      }
    },

    // 暂停/播放
    handlerPause () {
      // 播放列表判空
      if (this.emptyplayList()) return this.showMessage('播放列表为空')

      // 默认第一首播放
      if (this.currentPlayMusicIndex === -1) {
        this.updatePlayIndex(0)
      }

      // 清除定时器
      clearInterval(volumeFadeOut)
      clearInterval(volumeFadeIn)
      if (this.AudioPlayer) {
        var speed = 10
        if (this.AudioPlayer.paused) { // 未播放
          this.AudioPlayer.play()
          this.volume = 0
          var volumeFadeIn = setInterval(() => {
            this.volume += 1
            // console.log('volume adding', this.volume)
            if (this.volume >= this.apparentVolume) {
              clearInterval(volumeFadeIn)
              this.volume = this.apparentVolume
            }
          }, speed)
        } else {
          var volumeFadeOut = setInterval(() => {
            this.volume -= 1
            // console.log('volume reduce', this.volume)
            if (this.volume <= 0) {
              clearInterval(volumeFadeOut)
              this.AudioPlayer.pause()
              // console.log('pause', this.volume)
              this.volume = 0
            }
          }, speed)
        }
      }

      // console.log(this.AudioPlayer)
    },

    // 上一曲
    handlerPrev () {
      if (this.emptyplayList()) return this.showMessage('播放列表为空')
      this.updatePlayIndex((this.currentPlayMusicIndex - 1 + this.musicList.length) % this.musicList.length)
      // 恢复音量
      if (!this.volume) {
        this.volume = this.apparentVolume
      }
      if (this.currentPlayMode === 1) { // 如果是随机播放
        this.randomPlay()
      }
    },

    // 下一曲
    handlerNext () {
      if (this.emptyplayList()) return this.showMessage('播放列表为空')
      this.updatePlayIndex((this.currentPlayMusicIndex + 1 + this.musicList.length) % this.musicList.length)
      // 恢复音量
      if (!this.volume) {
        this.volume = this.apparentVolume
      }
      if (this.currentPlayMode === 1) { // 如果是随机播放
        this.randomPlay()
      }
    },

    // 播放列表判空
    emptyplayList () {
      if (this.musicList.length === 1 && Object.keys(this.musicList[0]).length === 3) return true
      return false
    },

    // 静音
    handlerMute () {
      if (this.volume) { // 触发静音，记录静音前的音量大小
        this.beforeMutedVolume = this.volume
        this.volume = 0
        this.apparentVolume = 0
      } else { // 开启声音
        this.volume = this.beforeMutedVolume
        this.apparentVolume = this.beforeMutedVolume
      }
    },

    // 绑定音乐播放完毕ended事件
    musicEnded (fn) {
      this.AudioPlayer.onended = () => { fn() }
    },

    // 切换播放模式
    handlerMode () {
      this.currentPlayMode = (this.currentPlayMode + 1) % this.playModeList.length
      this.bindEnded(this.currentPlayMode)
      // console.log(this.volume)
    },

    // 根据播放模式绑定onended事件
    bindEnded (mode) {
      switch (mode) {
        case 0: // 列表循环
          this.musicEnded(this.listLoop)
          break;
        case 1: // 随机播放
          this.musicEnded(this.randomPlay)
          break;
        // case 2: // 顺序播放
        //   this.musicEnded(this.orderPlay)
        //   break;
        case 2: // 单曲循环
          this.musicEnded(this.singleLoop)
          break;
        default:
          break;
      }
    },

    // 列表循环
    listLoop () {
      this.handlerNext()
      // console.log('列表循环')
    },

    // 随机播放
    randomPlay () {
      var i = Math.floor(Math.random() * this.musicList.length)
      while (i === this.currentPlayMusicIndex) {
        i = Math.floor(Math.random() * this.musicList.length)
      }
      this.updatePlayIndex(i)
      // console.log('随机播放')
    },

    // 顺序播放
    orderPlay () {
      // 判别1：判断是否为最后一首，若是，则停止播放
      // if (this.currentPlayMusicIndex === this.musicList.length - 1) {
      //   this.AudioPlayer.pause()
      // } else {
      //   this.handlerNext()
      // }

      // 判别2：判断是否全部播放完毕，若是，则停止播放
      // 已播放数加1
      this.hasPlayedMusicNum++
      if (this.hasPlayedMusicNum === this.musicList.length) {
        this.AudioPlayer.pause()
        this.hasPlayedMusicNum = 0
      } else {
        this.handlerNext()
      }
      // console.log('顺序播放')
    },

    // 单曲循环
    singleLoop () {
      // 不执行任何操作
      // console.log('单曲循环')
    },

    // 添加收藏
    collectMusic (row) {
      this.add2LovedList(row)
      row.loved = true
      return this.showMessage('收藏成功')
    },

    // 取消收藏
    cancelCollectMusic (row) {
      this.deleteOneFromLovedList(this.findIndexByTime(this.lovedList, row.time))
      row.loved = false
      return this.showMessage('已取消收藏')
    },

    // 添加到我喜欢
    handlerLike () {
      this.hasCollected = !this.hasCollected
    },

    // 拖拽音量滑块事件
    switchVolume () {
      this.volume = this.apparentVolume
    },

    // 根据歌曲time查找其索引
    findIndexByTime (arr, time) {
      return arr.findIndex(v => {
        return v.time === time
      })
    },

    // 提示信息
    showMessage (text) {
      this.$message({
        dangerouslyUseHTMLString: true,
        center: true,
        duration: 1800,
        message: '<p style="color: #009a61;font-size: 15px;">' + text + '</p>',
      })
    },

    // 手机端列表删除所有
    deleteAll (type) {
      // 0: 播放列表
      // 1: 收藏列表
      // 2: 播放历史
      console.log(type)
      switch (type) {
        case 0:
          this.deleteMoreFromPlayList(this.playList)
          break
        // case 1:
        //   this.deleteMoreFromLovedList(this.lovedList)
        //   break
        case 1:
          this.deleteMoreFromRecordList(this.recordList)
          break
        default:
          break
      }
    },

    // 手机端列表删除一个
    deleteOne (v, type) {
      switch (type) {
        case 0:
          let i = this.findIndexByTime(this.playList, v.time)
          this.deleteOneFromPlayList(i)
          break
        // case 1:
        //   let j = this.findIndexByTime(this.lovedList, v.time)
        //   v.loved = false
        //   this.deleteOneFromLovedList(j)
        //   break
        case 1:
          let k = this.findIndexByTime(this.recordList, v.time)
          this.deleteOneFromRecordList(k)
          break
        default:
          break
      }
    },

    // 手机端列表元素点击事件，播放选中音乐
    handlerMobileList (v, i, type) {
      if (type === 0) {
        this.updatePlayIndex(i)
      } else {
        let m = this.findIndexByTime(this.playList, v.time)
        if (m === -1) { // 播放列表中没有，则添加到播放列表，并播放
          this.add2PlayList(v)
          this.updatePlayIndex(this.playList.length - 1)
        } else {
          this.updatePlayIndex(m)
        }
      }

    },

    // 歌曲高亮
    highLight (type, v) {
      let i = this.findIndexByTime(this.playList, v.time)
      if (type === 0 && this.currentPlayMusicIndex === i)
        return 'highLight'
    },

    // 初始化轮播插件
    initSwiper () {
      var swiper = new Swiper('.swiper-container', {
        slidesPerView: 1,
        spaceBetween: 0,
        loop: false,
        speed: 500,
        autoplay: false,
        autoplayDisableOnInteraction: false,
        disableOnInteraction: true,
        observer: true,
        observeParents: true,
        pagination: '.swiper-pagination',
        paginationClickable: true,
        mousewheelControl: true,
        debugger: true,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        }
      })
    }
  },
}
</script>
    
<style lang="scss">
@import ".././css/player-tmp.scss";
</style>
